<template>
  <k-form-modal
    drawer
    :title="`${isEdit ? '更新' : '新增'}岗位`"
    label-width="80px"
    v-bind="formModalState"
    v-on="formModalEvent"
  >
    <h4 class="mb-10">岗位名称</h4>
    <el-form-item label="岗位名称" prop="role_name" :rules="[{ required: true, message: '请输入岗位名称' }]">
      <el-input v-model="state.model.role_name" placeholder="请输入岗位名称（必填）" />
    </el-form-item>
    <el-form-item label="岗位说明" prop="role_desc" :rules="[{ required: true, message: '请先填写岗位说明' }]">
      <el-input v-model="state.model.role_desc" placeholder="请先填写岗位说明（必填）" maxlength="20" show-word-limit />
    </el-form-item>
    <el-form-item label="岗位状态">
      <el-switch
        v-model="state.model.is_frozen"
        class="ml-2"
        width="40"
        inline-prompt
        :active-value="false"
        :inactive-value="true"
        active-text="开"
        inactive-text="关"
      />
    </el-form-item>
    <h4 class="mb-10">权限管理</h4>

    <div v-for="item in roleAuthList" :key="item.group_name" class="ml-10">
      <el-checkbox v-model="item.checkAll" :indeterminate="item.indeterminate" @change="handnleCheckAll(item)">{{ item.group_name }}</el-checkbox>
      <el-checkbox-group v-model="item.checkedData" class="ml-20" @change="handleItemChange(item)">
        <el-checkbox
          v-for="groupItem in item.items"
          :key="groupItem.func_id"
          :label="groupItem.func_id"
          :disabled="groupItem.disabled"
        >{{ groupItem.name }}</el-checkbox>
      </el-checkbox-group>
    </div>
  </k-form-modal>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useFormModal } from '@crud/index';
import { addRole, updateRole, getRoleFuncList } from '@/api/crm-kgj/auth';

defineOptions({ name: 'JobAuthEditDrawer' });

const formRef = ref();
const emits = defineEmits(['after-submit']);
const isEdit = ref(false);
const roleAuthList = ref([]);
/** 当前可提供的权限 */
const currentAuthList = ref([]);
const { state, formModalState, formModalEvent, ...methods } = useFormModal({
  formRef,
  model: {
    remark: '',
    product_type: 1,
    level: 20,
    month: 1,
    slave_count: 1
  },
  getParams: (model) => model,
  onShow: (mode = 0, data: any) => {
    roleAuthList.value = [];
    currentAuthList.value = [];
    isEdit.value = !!mode;
    if (mode === 0) {
      methods.resetModel();
    } else if (data) {
      state.model = { ...state.model, ...data };
      currentAuthList.value = data?.func_ids ?? [];
    }
    handleGetAuthList();
  },
  onSubmit: async (model, mode = 0) => {
    let funcIds = [];
    roleAuthList.value.forEach((item) => {
      funcIds.push(...item.checkedData);
    });
    if (!funcIds?.length) {
      ElMessage.error('请至少选择一个权限');
      return Promise.reject();
    }
    /** 将原有的权限设置为空，用新的权限配置替换 */
    model.func_ids = undefined;
    const { role_id, role_name, role_desc, is_frozen } = model;
    const params = {
      role_id,
      role_name,
      role_desc,
      is_frozen,
      func_id: funcIds
    };
    const res = await (isEdit.value ? updateRole(params) : addRole(params));
    if (!res.err) {
      ElMessage.success('更新成功');
      emits('after-submit');
    }
    return res;
  }
});
/** 获取权限列表 */
const handleGetAuthList = async () => {
  const res:any = await getRoleFuncList();
  let data = res.data.map((e) => {
    return { ...e, checkAll: false, indeterminate: false, checkedData: [], frontData: [] };
  });
  if (!res.err) {
    currentAuthList.value.forEach((item) => {
      data.forEach((item2) => {
        item2.items.find((item3) => {
          if (item3.func_id === item) {
            item2.checkedData.push(item);
            item3.front_items.forEach((item4) => {
              const frontItem = item2.frontData.find((item5) => item5 === item4);
              !frontItem && item2.frontData.push(item4);
            });
          }
        });
        item2.frontData.forEach((val) => {
          item2.items.find((val2) => {
            if (val2.func_id === val) {
              val2.disabled = true;
            }
          });
        });
        item2.checkAll = item2.checkedData.length === item2.items.length;
        item2.indeterminate = item2.checkedData.length > 0 && item2.checkedData.length < item2.items.length;
      });
    });
  }
  roleAuthList.value = data;
};
/** 选中其中一条权限下的所有子权限 */
const handnleCheckAll = (item) => {
  if (!item.checkedData.length) {
    // 让前置条件为disabled
    item.items.forEach((val) => {
      item.checkedData.push(val.func_id);
      val.front_items?.forEach((val2) => {
        const frontItem = item.frontData.find((val3) => val2 === val3);
        !frontItem && item.frontData.push(val2);
      });

      item.frontData.forEach((val2) => {
        const disabledItem = item.items.find((val3) => val3.func_id === val2);
        disabledItem && (disabledItem.disabled = true);
      });
    });
    item.checkAll = item.checkedData.length === item.items.length;
    item.indeterminate = !item.checkAll;
  } else {
    // 取消全选时disabled为false
    item.items.forEach((val) => (val.disabled = false));
    item.checkedData = [];
    item.frontData = [];
    item.checkAll = false;
    item.indeterminate = false;
  }
};
/** 选中其中一个子权限 */
const handleItemChange = (item) => {
  const checkedDataLen = item.checkedData?.length;
  const itemsLen = item.items?.length;
  item.checkAll = checkedDataLen === itemsLen;
  item.indeterminate = checkedDataLen > 0 && checkedDataLen < itemsLen;

  item.frontData = [];
  item.checkedData.forEach((val) => {
    const checkedItem = item.items.find((val2) => val === val2.func_id);
    checkedItem?.front_items?.forEach((val2) => {
      const frontItem = item.frontData.find((val3) => val2 === val3);
      !frontItem && item.frontData.push(val2);
    });
  });
  item.items.forEach((val) => (val.disabled = false));
  item.frontData.forEach((val) => {
    item.items.find((val2) => {
      if (val2.func_id === val) {
        val2.disabled = true;
        const exitChecked = item.checkedData.find((val3) => val3 === val);
        !exitChecked && item.checkedData.push(val);
      }
    });
  });
};
defineExpose({
  show: methods.show
});
</script>
